import queue
import concurrent.futures
import threading
import workItem
import requests

#工作队列
work_queue = queue.Queue()
#工作项并发
executor = concurrent.futures.ThreadPoolExecutor(max_workers=None)

class GetItemThread(threading.Thread):
    def run(self):
        while True:
            #获取需要下载的项
            item = work_queue.get()
            if item.type == -1:
                break
            #
            executor.submit(downloadFile,item)
#
getItemThread = GetItemThread()

def addWorkItem(item):
    work_queue.put(item)

def downloadFile(item):
    try:
        item.count += 1
        res = requests.get(item.url,timeout=60)
        #保存文件
        with open(item.filePath,'wb') as f:
            f.write(res.content)
            print("\n下载 [{}] [{}] {} 完成".format(item.order,len(res.content),item.fileName))
        item.isSuccess = True
        #有一项任务完成
        work_queue.task_done()
    except Exception as ex:
        #出现异常，就重新放到队列中
        if item.count < 6:
            work_queue.put(item)
        print("\n异常 [{}] {} {}".format(item.order,item.fileName,ex))
    else:
        return

def startToWork():
    getItemThread.start()

def exitWork():
    work_queue.put(workItem.WorkItem('','','','',type=-1))

def wait():
    work_queue.join()

